package com.choudou5.service;

import cn.hutool.core.util.RandomUtil;
import com.choudou5.entity.UserAddress;
import com.choudou5.entity.UserInfo;
import com.choudou5.mapper.UserAddressMapper;
import com.choudou5.mapper.UserInfoMapper;
import com.choudou5.utils.IdGenUtil;
import com.choudou5.utils.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CommonService {

    private final static Logger logger = LoggerFactory.getLogger(CommonService.class);

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;

    @Transactional
    public void add() {
        long id = IdGenUtil.genId();
        UserInfo userInfo = new UserInfo("zhangsan", 12);
        userInfoMapper.insert(userInfo);
        logger.info("睡眠开始");
        ThreadUtil.sleep(3000);
        logger.info("睡眠结束");
        userAddressMapper.insert(new UserAddress("广州", "天河区" + RandomUtil.randomInt(4) + "号"));
        logger.info("第二次睡眠开始");
        ThreadUtil.sleep(3000);
        logger.info("第二次睡眠结束");
        userInfo.setAge(18);
        userInfoMapper.updateAge(userInfo);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void addTryCatch() {
        try{
            UserInfo userInfo = new UserInfo("zhangsan", 12);
            userInfoMapper.insert(userInfo);
            logger.info("睡眠开始");
            ThreadUtil.sleep(3000);
            logger.info("睡眠结束");
            userAddressMapper.insert(new UserAddress("广州", "天河区" + RandomUtil.randomInt(4) + "号"));
            logger.info("第二次睡眠开始");
            ThreadUtil.sleep(3000);
            logger.info("第二次睡眠结束");
            userInfo.setAge(18);
            userInfoMapper.updateAge(userInfo);
        }catch(Exception e){
            logger.error(" 操作支付订单失败", e);
            throw e;
        }
    }


    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public void addTryCatchThrowable() {
        try{
            UserInfo userInfo = new UserInfo("zhangsan", 12);
            userInfoMapper.insert(userInfo);
            logger.info("睡眠开始");
            ThreadUtil.sleep(3000);
            logger.info("睡眠结束");
            userAddressMapper.insert(new UserAddress("广州", "天河区" + RandomUtil.randomInt(4) + "号"));
            logger.info("第二次睡眠开始");
            ThreadUtil.sleep(3000);
            logger.info("第二次睡眠结束");
            userInfo.setAge(18);
            userInfoMapper.updateAge(userInfo);
        }catch(Exception e){
            logger.error(" 操作支付订单失败", e);
            throw e;
        }
    }

}
